<?php
/**
 * 后台管理员模型
 * Author: lyun
 * Date: 2018/3/23
 * Created by Panxsoft.
 */


namespace App\Models\Admin;

use App\Models\Concerns\DeSensitive;
use App\Models\Concerns\ScopeFilterable;
use App\Models\Customer\Customer;
use App\Models\OpenWechat\WechatUser;
use App\Models\Panx\SkinRecordBonus;
use App\Models\Store\SkinRecord;
use App\Models\Store\Store;
use App\Services\Utils\Guard;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject as AuthenticatableUserContract;

/**
 * Class StoreAdmin
 *
 * @property Store store
 * @property string name
 * @property WechatUser|null wechatUser
 * @property int id
 * @property int is_deleted
 * @property int store_id
 * @property int wechat_user_id
 * @property string account
 * @property string email
 * @property string language
 * @property int $received_consumer_count
 * @property string $ali_account
 * @property Collection skinRecordBonuses
 * @property string num
 * @property string total_amount
 * @property string headimgurl
 * @property Customer customer
 *
 * @method static self filterIsSuperMan()
 * @method static self filterHasSkinRecordBonusesGranted(int $bonus_status = SkinRecordBonus::BONUS_STATUS_SUCCESS)
 * @method static self role(string|array $roles)
 * @see HasRoles::scopeRole()
 *
 * @method static self filterWechatBoundAndSubscribed()
 *
 * @mixin Builder
 * @package App\Models\Admin
 */
class StoreAdmin extends Authenticatable implements
    CanResetPasswordContract,
    AuthenticatableUserContract
{
    use HasRoles;
    use ScopeFilterable;
    use DeSensitive;

    const IS_NOT_DELETED = 0; // 后台管理员启用
    const IS_DELETED = 1;     // 后台管理员禁用
    const GUARD_NAME = 'store'; // 后台guard

    const SUPER_MAN = '超管'; // 超管的角色
    const FINANCE = '财务';  // 财务的角色
    const STAFF = '店员';

    const ROLE_RELATION = [
        'SUPER_MAN' => self::SUPER_MAN,
        'FINANCE'   => self::FINANCE,
        'CLERK'     => self::STAFF,
    ];

    protected $guard_name = Guard::ADMIN_STORE;

    protected $table = 'store_admins';

    protected $guarded = [];

    protected $hidden = ['password', 'remember_token', 'reset_token'];

    protected $casts = [
        'id'             => 'int',
        'store_id'       => 'int',
        'wechat_user_id' => 'int',
        'sex'            => 'int',
        'is_deleted'     => 'int',
        'phone'          => 'string',
    ];

    /**
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey(); // Eloquent model method
    }

    /**
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id', 'id');
    }

    public function getCustomer(): ?Customer
    {
        return $this->store->customer ?? null;
    }

    /**
     * @param $value
     * @return mixed
     */
    public function setPasswordAttribute(?string $value)
    {
        if ($value) {
            return $this->attributes['password'] = Hash::make($value);
        }
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function wechatUser()
    {
        return $this->belongsTo(WechatUser::class, 'wechat_user_id', 'id');
    }

    public function skinRecords()
    {
        return $this->hasMany(SkinRecord::class, 'store_admin_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
     */
    public function skinRecordBonuses()
    {
        return $this->morphMany(SkinRecordBonus::class, 'bonusable');
    }

    /**
     * 微信用户绑定且处于关注状态
     *
     * @param Builder $query
     * @return Builder
     */
    public function scopeFilterWechatBoundAndSubscribed(Builder $query)
    {
        return $query->whereHas('wechatUser', function (Builder $builder) {
            /** @var WechatUser $builder */
            $builder->filterSubscribed();
        });
    }

    /**
     * @used-by filterIsSuperMan
     *
     * @param Builder $query
     * @return Builder
     */
    public function scopeFilterIsSuperMan(Builder $query)
    {
        return $query->where('id', '<>', Guard::storeAdmin()->id);
    }

    /**
     * @used-by filterHasSkinRecordBonusesGranted - 过滤有测肤红包，并默认为发放成功状态的
     *
     * @param Builder $query
     * @param int $bonus_status
     *
     * @return Builder
     */
    public function scopeFilterHasSkinRecordBonusesGranted(Builder $query,
                                                           int $bonus_status = SkinRecordBonus::BONUS_STATUS_SUCCESS)
    {
        return $query->whereHas('skinRecordBonuses', function (Builder $query) use ($bonus_status) {
            $query->where('bonus_status', $bonus_status);
        });
    }

    /**
     * @return bool
     */
    public static function checkIsSuperMan()
    {
        /** @var StoreAdmin $store_admin */
        $store_admin = Guard::storeAdmin();

        return $store_admin->isSuperMan();
    }

    /**
     * @return bool
     */
    public function isSuperMan(): bool
    {
        return $this->hasRole(self::SUPER_MAN);
    }
}
